<template>
	<view class="page" :style="{'padding-bottom': pad + 'rpx'}">
		<view v-if="alReponses || list.length>0">
			<scroll-view class="scoll-box" :scroll-top="scrollTop" :scroll-y="true">
				<view id="scrollView" style="padding-bottom: 100rpx;">
					<view class="list-box">
						<view class="item" v-for="(item,index) in list" :key="index">
							<view style="line-height: 60rpx;"><mp-html :content="marked(item)" /></view>
							<view style="margin-top: 20rpx;"><u--text @click="copyContent" size="26rpx" type="primary" text="复制"></u--text></view>
						</view>
					</view>
					<view
					  style="display: flex;align-items: center;padding: 20rpx 40rpx;background: #fff; margin: auto;margin-top: 20rpx;"
					  v-if="thinking"
						>
						<text>思考中</text>
						<view class="text">
							<view class="bar"></view>
							<view class="bar"></view>
							<view class="bar"></view>
						</view>
					</view>
					<view class="answer-box" v-if="alReponses">
						<view style="line-height: 60rpx;">
							<mp-html :content="marked(alReponses)+(lightShow ? `<div class='light-icon'></div>` : '')" />
						</view>
						<view class="title" v-if="!lightShow">
							AI 生成内容仅供参考，不代表平台立场。
						</view>
						<view class="answer-btn" v-if="!lightShow">
							<view class="lleft"><button class="sbtn" open-type="share">zhu</button> <u--text size="26rpx"
									type="primary" text="分享"></u--text><u--text @click="copyContent" size="26rpx" type="primary"
									text="复制"></u--text></view>
							<view class="rright"><u--text @click="againSubmit" size="26rpx" type="primary" text="重新生成"></u--text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>
		</script>
		<view class="form-box" v-if="info && !alReponses && list.length<=0">
			<u--form labelPosition="left" ref="uForm">
				<block v-for="(item,index) in info.form" :key="index">
					<view style="margin-top: 40rpx;">
						<u-form-item labelWidth="600rpx" :label="item.title" prop="userInfo.name"
							:borderBottom="false" :required="item.required==1" labelPosition='top'
							v-if="item.type=='input'">
							<view style="margin-top: 20rpx;">
							</view>
							<u--input v-model="item.value" border="none" :placeholder="item.placeholder"></u--input>
						</u-form-item>
					</view>
					<view style="margin-top: 40rpx;">
						<u-form-item labelWidth="600rpx" :label="item.title" prop="userInfo.sex"
							:borderBottom="false" :required="item.required==1" @click="showSex = true"
							labelPosition='top' v-if="item.type=='select'">
							<view style="margin-top: 20rpx;">
							</view>
							<u--input v-model="item.value" disabled disabledColor="#ffffff" :placeholder="item.placeholder"
								border="none"></u--input>
							<u-icon slot="right" name="arrow-right"></u-icon>
						</u-form-item>
					</view>
					<view style="margin-top: 40rpx;">
						<u-form-item labelWidth="600rpx" :label="item.title" prop="userInfo.name"
							:borderBottom="false" required labelPosition='top'
							:required="item.required==1" v-if="item.type=='number'">
							<view style="margin-top: 20rpx;">
							</view>
							<u--input v-model="item.value" border="none" :placeholder="item.placeholder"
								type="number"></u--input>
						</u-form-item>
					</view>
					<view style="margin-top: 40rpx;">
						<u-form-item labelWidth="600rpx" :label="item.title" prop="userInfo.name"
							:borderBottom="false" required labelPosition='top'
							:required="item.required==1" v-if="item.type=='textarea'">
						
							<view style="margin-top: 20rpx;">
							</view>
							<u--textarea v-model="item.value" :placeholder="item.placeholder" count
								:maxlength="item.max_length >0?item.max_length:999"></u--textarea>
						</u-form-item>
					</view>
				</block>
			</u--form>
			<u-action-sheet :show="showSex" :actions="actions" title="" @close="showSex = false">
			</u-action-sheet>
		</view>
		<view class="btn-box" v-if="info && !alReponses && list.length==0">
			<view class="btn">
				<u-button color="#FF6005" type="primary" shape="circle" :disabled="isLoading" text="重置" :plain="true"
					@click="clearFun"></u-button>
			</view>
			<view class="btn">
				<u-button color="#FF6005" :loading="isLoading" type="primary" shape="circle" text="生成内容"
					@click="submitFun"></u-button>
			</view>
		</view>
		<view class="btn-box btn-box2" v-if="alReponses && !lightShow">
			<view class="btn">
				<u-button color="#FF6005" type="primary" shape="circle" text="再写一篇" :plain="true"
					@click="againFun"></u-button>
			</view>
			<view class="btn">
				<u-button color="#FF6005" type="primary" shape="circle" text="试试AI对话"
					@click="toAiDialog"></u-button>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		marked
	} from "marked";
	import hljs from "highlight.js";
	import mpHtml from "mp-html/dist/uni-app/components/mp-html/mp-html";
	import "highlight.js/scss/atom-one-dark.scss";
	import {
		aiSubmit,
		createDialog
	} from '@/api/index.js'
	export default {
		components: {
			mpHtml
		},
		data() {
			return {
				isLoading:false,
				scrollTop:0,
				list: [],
				lightShow: false,
				marked: marked,
				alReponses: '',
				alReponse: '',
				sessionId:'',
				chartNumber: 0,
				actions: [{
						name: '正式得体',
						value: 0
					},
					{
						name: '严肃庄重',
						value: 1
					},
					{
						name: '有说服力',
						value: 2
					},
					{
						name: '轻松',
						value: 3
					},
					{
						name: '热情',
						value: 4
					}
				],
				showSex: false,
				info: '',
				pad: 0,
				thinking: false
			};
		},
		onLoad(option) {
			const arr = JSON.parse(option.item)
			this.info = arr
			uni.setNavigationBarTitle({
				title: arr.title
			})
			this.initHighLight();
		},
		onShareTimeline() {
			return {
				title: this.info.title,
				query: 'item=' + this.info
			}
		},
		onShareAppMessage() {
			return {
				title: this.info.title,
				path: '/pages/ai-create/detail/detail'
			}
		},
		watch: {
			alReponse(newValue) {
				if (this.chartNumber == 0 || this.chartNumber != this.alReponse.length) {
					this.chartWhite()
					this.scrollToBottom()
				}
			}
		},
		onShareAppMessage() {
			return {
				title: "爱云艺",
				path: "/pages/ai-create/detail/detail?item=" + JSON.stringify(this.info)
			}
		},
		methods: {
			//滚动到底部
			scrollToBottom() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('#scrollView').boundingClientRect();
					query.exec((res) => {
						if(res && res[0] && res[0].height){
							
						this.scrollTop = res[0].height+50; // 设置滚动条到达底部
						}
					});
				});
			},
			againSubmit() {
				this.pad = 0
				this.list.push(this.alReponse)
				this.chartNumber = 0
				this.alReponses = ''
				this.alReponse = ''
				this.thinking = true
				this.submitFun()
			},
			copyContent() {
				const query = uni.createSelectorQuery().in(this);
				uni.setClipboardData({
					data: this.alReponses
				})
			},
			toAiDialog() {
				uni.navigateTo({
					url: '/pages/ai-create/ai-dialog/ai-dialog'
				})
			},
			againFun() {
				this.chartNumber = 0
				this.alReponses = ''
				this.list=[]
				this.thinking = true
			},
			//清空
			clearFun() {
				let arr = this.info.form
				arr.forEach(item => {
					item.value = ''
				})
			},

			chartWhite() {
				if (this.chartNumber < this.alReponse.length) {
					this.alReponses += this.alReponse.charAt(this.chartNumber)
					this.chartNumber++
					setTimeout(this.chartWhite, 100) //控制打字速度
				}
			},
			submitFun() {
				if(!uni.getStorageSync('apiticket')){
					console.log('detail里面')
					uni.showModal({
						title: "提示",
						content: "请登录",
						success(res) {
							if(res.confirm){
								setTimeout(() => {
									uni.navigateTo({
										url: "/pages/login/index",
									})
								}, 1000);
							}
						},
					});
					return
				}
				this.thinking = true
				this.isLoading=true
				let arr = this.info.form
				let obj = {}
				for (let i = 0; i < arr.length; i++) {
					obj[arr[i].name] = arr[i].value
				}
				if(this.sessionId){
					const param = {
						product_code: this.info.product_code,
						form: JSON.stringify(obj),
						session_id:this.sessionId
					}
					aiSubmit(param).then(res => {
						console.log(res)
						if (res && res.errcode == 200) {
							this.connectWeb(res)
							this.lightShow = true
							this.pad = 200
							this.thinking = false
						} else {
							this.isLoading=false
							// uni.hideLoading()
							uni.showToast({
								title: res.errmsg,
								icon: 'none',
								duration: 5000
							})
							this.thinking = false
						}
					
					})
				}else{
					createDialog().then(res => {
						console.log(res)
						this.sessionId = res.session_id
						const param = {
							product_code: this.info.product_code,
							form: JSON.stringify(obj),
							session_id:res.session_id
						}
						aiSubmit(param).then(res => {
							console.log(res)
							if (res && res.errcode == 200) {
								this.connectWeb(res)
								this.lightShow = true
								this.pad = 200
								this.thinking = false
							} else {
								this.isLoading=false
								// uni.hideLoading()
								uni.showToast({
									title: res.errmsg,
									icon: 'none',
									duration: 5000
								})
								this.thinking = false
							}
						
						})
					})
				}
				
				
				
			},
			connectWeb(res) {
				const webs = uni.connectSocket({
					url:'wss://'+res.domain+'/chat/?uid='+res.uid+'&session_id='+res.session_id+'&openid='+res.openid,
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						console.log(res)
					},
					fail: (err) => {
						console.log(err)
					}
				})
				webs.onOpen((e) => {
					// uni.hideLoading()
					console.log('open', e)
				})
				webs.onError((e) => {
					// uni.hideLoading()
					uni.showToast({
						title: '连接失败，请稍后再试',
						icon: "none"
					})
					console.log('err', e)
				})
				webs.onMessage((e) => {
					if (e.data == 'Done') {
						this.lightShow = false
						this.thinking = false
						webs.close()
						return
					} else {
						if(this.isLoading){
							this.isLoading=false
						}
						this.thinking = false
						this.alReponse += e.data
					}
				})
				webs.onClose((e) => {
					console.log('close', e)
				})
			},
			initHighLight() {
				hljs.configure({
					useBR: true,
					tabReplace: " ",
				});
				marked.setOptions({
					renderer: new marked.Renderer(),
					gfm: true,
					tables: true,
					breaks: false,
					pedantic: false,
					highlight: function(code, lang) {
						if (lang && hljs.getLanguage(lang)) {
							return hljs.highlight(lang, code, true).value;
						} else {
							return hljs.highlightAuto(code).value;
						}
					},
				});
			},
		}
	}
</script>

<style>
	@keyframes cursor-blink {

		0%,
		50% {
			opacity: 1;
			/* 光标可见 */
		}

		51%,
		100% {
			opacity: 0;
			/* 光标不可见 */
		}
	}

	.light-icon {
		width: 2px;
		height: 10px;
		background-color: skyblue;
		animation: cursor-blink 1s infinite step-end;
		/* 光标闪烁动画 */
	}
</style>
<style lang="scss" scoped>
	.scoll-box{
		// height: calc(100vh - var(--status-bar-height)  - 120rpx);
		height: calc(100vh - 120rpx);
	}
	.list-box{
		width: 92%;
		margin: auto;
		.item{
			padding: 20rpx 20rpx;
			background-color: #fff;
			margin-top: 20rpx;
			box-sizing: border-box;
			border-radius: 10rpx;
		}
	}
	.page {
		padding-bottom: 200rpx;
	}

	.answer-box {
		background-color: #fff;
		padding: 20rpx 40rpx;
		box-sizing: border-box;
		width: 92%;
		margin: auto;
		border-radius: 10rpx;
		margin-top: 20rpx;

		.answer-btn {
			display: flex;
			justify-content: space-between;
			width: 100%;
			border-top: 1px solid #f4f4f4;
			margin-top: 20rpx;
			padding-top: 20rpx;
			box-sizing: border-box;

			.lleft {
				display: flex;
				justify-content: space-between;
				width: 160rpx;
				position: relative;

				.sbtn {
					position: absolute;
					left: 0;
					top: 0;
					width: 70rpx;
					height: 60rpx;
					opacity: 0;
				}
			}
		}

		.title {
			font-size: 24rpx;
			color: #acacac;
			margin-top: 20rpx;
		}
	}

	.btn-box {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin: auto;
		background-color: #fff;
		padding: 40rpx 60rpx;
		box-sizing: border-box;
		
		.btn {
			width: 40%;
		}
	}

	.btn-box2 {
		position: fixed;
		bottom: 0;
		left: 0;
		height: 160rpx;
	}

	.form-box {
		padding: 20rpx 40rpx;
		box-sizing: border-box;
		background-color: #fff;

	}
	
	@keyframes bounce {
	
		0%,
		100% {
			transform: translateY(6rpx);
		}
	
		50% {
			transform: translateY(-6rpx);
		}
	}
	
	.text {
		font-size: 32rpx;
		font-weight: 600;
		display: flex;
		height: 24rpx;
	
		.bar {
			animation: bounce 1s infinite;
			background: linear-gradient(to top, #6F31F4, #FF6005);
			height: 10rpx;
			width: 10rpx;
			margin-left: 6rpx;
		}
	
		.bar:nth-child(1) {
			animation-delay: 0s;
		}
	
		.bar:nth-child(2) {
			animation-delay: 0.1s;
		}
	
		.bar:nth-child(3) {
			animation-delay: 0.2s;
		}
	}
</style>